package com.liu.fiter;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import com.google.common.collect.Maps;
public class TPMonitor implements Runnable{

    public static final long VALID_TIME = 1000*60;
    // 存储请求时间和请求耗时
    private Map<Long,Long> useTimeMaps = new ConcurrentHashMap<>(1000);

    // 堆外暴露调用接口存储耗时
    public void request(Long requestTime,Long useTime){
        useTimeMaps.put(requestTime,useTime);
    }

    // 请求过期数据
    private void clearOld(){
        long valid = System.currentTimeMillis()-VALID_TIME;
        Set<Long> requestTimes = useTimeMaps.keySet();
        for (Long r:requestTimes){
            if(r<valid){
                useTimeMaps.remove(r);
            }
        }
    }

    // 开启线程每5s打印一次TP90和TP99
    @Override
    public void run() {
        while (true){
            try {
                Thread.sleep(5000);
                final Map<Long,Long> temp = Maps.newHashMap(useTimeMaps);
                int total = temp.size();
                if (total == 0){
                    continue;
                }
                clearOld();
                int tp90 = (int) (total*0.9);
                int tp99 = (int) (total*0.99);
                final Collection<Long> requestTimes = temp.values();

                Object[] sortedRequestTimes = requestTimes.stream().sorted().toArray();
                System.out.println("=====>>>>> tp90:"+sortedRequestTimes[tp90]+"ms");
                System.out.println("=====>>>>> tp99:"+sortedRequestTimes[tp99]+"ms");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
